PATHMac OS 8 and 9 Developer Documentation > Interapplication Communication > AppleScript for Scripters >

AppleScript Language Guide

   

Repeat With (loopVariable) In (list)

In the Repeat With (loopVariable) In (list) form of the Repeat statement, the loop variable is a reference to an item in a list. The number of iterations is equal to the number of items in the list. In the first iteration, the value of the variable is item 1 of list (where list is the list you specified in the first line of the statement), in the second iteration, its value is item 2 of list , and so on.

SYNTAX
repeat with loopVariable in list
    [ statement ]...
end [ repeat ]

where

loopVariable is any previously defined variable or a new variable you define in the Repeat statement (see "Notes").

list is a list or a reference (such as words 1 thru 5 ) whose value is a list.

list can also be a record; AppleScript coerces the record to a list (see "Notes").

statement is any AppleScript statement.

EXAMPLE

The following script examines a list of words with the Repeat With (loopVariable) In (list) form of the Repeat statement, displaying a dialog if it finds the word "hammer" in the list.

set wordList to words in "Where is the hammer?"
repeat with currentWord in wordList
    --log currentWord
    if currentWord as text is equal to "hammer" then
        display dialog "I found the hammer!"
    end if
end repeat

For a description of the commented-out statement --log currentWord, see Debugging Control Statements.

NOTES

You can use an existing variable as the loop variable in a Repeat statement or define a new one in the Repeat statement. In either case, the loop variable is defined outside the loop. You can change the value of the loop variable inside the loop body but it will get reset to the next loop value the next time through the loop. After the loop completes, the loop variable retains its last value.

AppleScript evaluates loopVariable in list as item 1 of list. item 2 of list. item 3 of list , and so on until it reaches the last item in the list, as shown in the following example.

repeat with i in {1, 2, 3, 4}
    set x to i
end repeat
--result: item 4 of {1, 2, 3, 4}

To set a variable to the value of an item in the list, rather than a reference to the item, you can use the contents of operator:

repeat with i in {1, 2, 3, 4}
    set x to contents of i
end repeat
--result: 4

You can also use the list items directly in expressions:

set x to 0
repeat with i in {1, 2, 3, 4}
    set x to x + i
end repeat
--result: 10

If the value of list is a record, AppleScript coerces the record to a list by stripping the property labels. For example, {a:1, b:2, c:3} becomes {1, 2, 3} .


© 1999 Apple Computer, Inc. – (Last Updated 21 May 99)